/*******************************************************************************
 * Package: com.song.boot.springstudy.thread.lock
 * Type:    WaitNotify
 * Date:    2024-06-25 17:38
 *
 * Copyright (c) 2024 LTD All Rights Reserved.
 *
 * You may not use this file except in compliance with the License.
 *******************************************************************************/
package com.song.boot.springstudy.thread.lock;

import lombok.SneakyThrows;

import java.util.concurrent.TimeUnit;

/**
 * 功能描述：  Java多线程中的 wait() 和 notify() 方法
 *https://blog.csdn.net/sinat_31583645/article/details/129614853
 * @author Songxianyang
 * @date 2024-06-25 17:38
 */
public class WaitNotify {

    public void waitTest(Object lock) throws InterruptedException {
        synchronized (lock) {
            lock.wait();
            System.out.println("线程等待！！！释放锁等待----"+Thread.currentThread().getName());
        }
    }


    @SneakyThrows
    private void notifyTest(Object lock) {
        synchronized (lock) {
            // lock.notify();
            lock.notifyAll();
            System.out.println("唤醒线程呀哈哈哈---（唤醒其中一个线程，去枪锁）"+Thread.currentThread().getName());
            TimeUnit.SECONDS.sleep(2);
        }
    }


    public static void main(String[] args) {
        Object lock = new Object();
        Thread thread = new Thread(()->{
            WaitNotify waitNotify = new WaitNotify();
            try {
                waitNotify.waitTest(lock);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"线程1");
        thread.start();

        Thread thread2 = new Thread(()->{
            WaitNotify waitNotify = new WaitNotify();
            try {
                waitNotify.waitTest(lock);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"线程2");
        thread2.start();

        Thread thread3 = new Thread(()->{
            WaitNotify waitNotify = new WaitNotify();
            waitNotify.notifyTest(lock);
        },"线程3");
        thread3.start();

    }
}
